"use client";
import { useState, useRef } from "react";
import { Carousel, Skeleton, Card, Divider } from "antd";
import { RightOutlined, LeftOutlined } from "@ant-design/icons";
import Notice from "../Notice/Index";
import { useCategories } from "@/hooks/useCategories";
import Image from "next/image";
import "antd/dist/reset.css";
import React from "react";

// 自定义样式
const arrowButtonStyle: React.CSSProperties = {
  backgroundColor: "rgba(0, 0, 0, 0.7)",
  transition: "all 0.3s ease",
  border: "none",
  outline: "none",
};

const arrowIconStyle: React.CSSProperties = {
  color: "white",
  transition: "color 0.3s ease",
};

const images = [
  "/images/banner1.png",
  "/images/banner2.png",
  "/images/banner3.png",
];
export default function Banner() {
  const [imageLoaded, setImageLoaded] = useState<Record<number, boolean>>({});
  const { categories, loading, error } = useCategories();
  const carouselRef = useRef<{ prev: () => void; next: () => void } | null>(
    null
  );
  const handleImageLoad = (index: number) => {
    setImageLoaded((prev) => ({ ...prev, [index]: true }));
  };

  const handlePrev = () => {
    carouselRef.current?.prev();
  };

  const handleNext = () => {
    carouselRef.current?.next();
  };
  const navigateToCategory = (categoryName: string) => {
    try {
      const encodedCategory = encodeURIComponent(categoryName);
      const url = `/products?condition.category=${encodedCategory}`;
      window.location.href = url;
    } catch (err) {
      console.error("导航失败:", err);
    }
  };
  const cardContentStyle: React.CSSProperties = {
    padding: "4px 4px",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: "4px",
  };

  const compactDividerStyle: React.CSSProperties = {
    margin: "0",
    backgroundColor: "#f0f0f0",
    height: "1px",
  };

  return (
    <section className="md:h-[400px] h-auto overflow-hidden">
      <div className="container mx-auto flex flex-col gap-2 md:flex-row items-center justify-between md:h-full">
        <div className="w-full md:w-1/6 md:h-full bg-white shadow-md p-2">
          {loading ? (
            <div className="space-y-2 p-2">
              {[1, 2, 3, 4, 5].map((i) => (
                <Skeleton.Button key={i} block size="large" />
              ))}
            </div>
          ) : error ? (
            <div className="w-full p-4 text-red-500 text-center">{error}</div>
          ) : (
            <div>
              {categories.map((category, index) => (
                <React.Fragment key={category.key}>
                  <Card
                    onClick={() => navigateToCategory(category.key)}
                    className="cursor-pointer hover:shadow-md transition-all duration-300 group"
                    variant="text"
                    style={{
                      border: "none",
                      boxShadow: "none",
                    }}
                  >
                    <div style={cardContentStyle}>
                      <div className="flex items-center gap-3">
                        <div className="transition-all duration-300 group-hover:text-[#1677ff] group-hover:scale-110 group-hover:rotate-6">
                          {category.icon}
                        </div>
                        <span className="transition-all duration-300 group-hover:text-[#1677ff] group-hover:text-xl group-hover:font-bold">
                          {category.label}
                        </span>
                      </div>
                      <RightOutlined
                        className="transition-all duration-300 text-gray-400 group-hover:text-[#1677ff] group-hover:scale-80 group-hover:rotate-12 group-hover:text-lg group-hover:font-bold"
                        style={{ fontSize: "14px" }}
                      />
                    </div>
                  </Card>
                  {/* 最后一项不显示分割线 */}
                  {index !== categories.length - 1 && (
                    <Divider style={compactDividerStyle} />
                  )}
                </React.Fragment>
              ))}
            </div>
          )}
        </div>

        <div className="w-full md:w-3/6 md:h-full relative mt-2 md:mt-0 group">
          <Carousel
            ref={carouselRef}
            className="h-[300px] md:h-full shadow-lg transition-all duration-300"
            autoplay
            effect="fade"
          >
            {images.map((img, index) => (
              <div
                key={index}
                className="relative h-[300px] md:h-[400px] bg-gray-100"
                // 确保每个轮播项占满容器
                style={{ position: "relative", height: "100%" }}
              >
                <Image
                  src={img}
                  alt={`轮播图 ${index + 1}`}
                  fill
                  className={`object-[100% 100%] transition-opacity duration-500 ${
                    imageLoaded[index] ? "opacity-100" : "opacity-0"
                  }`}
                  sizes="(max-width: 768px) 100vw, 50vw"
                  priority={index === 0}
                  onLoad={() => handleImageLoad(index)}
                />
              </div>
            ))}
          </Carousel>

          {/* 左箭头 */}
          <button
            onClick={handlePrev}
            className="absolute cursor-pointer left-2 top-1/2 transform -translate-y-1/2 z-10 text-white p-2 rounded-full opacity-0 group-hover:opacity-80 hover:opacity-100"
            aria-label="上一张"
            style={arrowButtonStyle}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = "#2563eb";
              e.currentTarget.style.transform = "translateY(-50%) scale(1.1)";
              // 直接设置图标颜色
              const icon = e.currentTarget.querySelector(".anticon");
              if (icon) {
                icon.style.color = "#fbbf24";
                icon.style.fontSize = "20px";
                icon.style.fontWeight = "bold";
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
              e.currentTarget.style.transform = "translateY(-50%) scale(1)";
              // 恢复图标颜色
              const icon = e.currentTarget.querySelector(".anticon");
              if (icon) {
                icon.style.color = "white";
                icon.style.fontSize = "18px";
                icon.style.fontWeight = "normal";
              }
            }}
          >
            <LeftOutlined className="text-lg" style={arrowIconStyle} />
          </button>

          {/* 右箭头 */}
          <button
            onClick={handleNext}
            className="absolute cursor-pointer right-2 top-1/2 transform -translate-y-1/2 z-10 text-white p-2 rounded-full opacity-0 group-hover:opacity-80 hover:opacity-100"
            aria-label="下一张"
            style={arrowButtonStyle}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = "#2563eb";
              e.currentTarget.style.transform = "translateY(-50%) scale(1.1)";
              // 直接设置图标颜色
              const icon = e.currentTarget.querySelector(".anticon");
              if (icon) {
                icon.style.color = "#fbbf24";
                icon.style.fontSize = "20px";
                icon.style.fontWeight = "bold";
              }
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.7)";
              e.currentTarget.style.transform = "translateY(-50%) scale(1)";
              // 恢复图标颜色
              const icon = e.currentTarget.querySelector(".anticon");
              if (icon) {
                icon.style.color = "white";
                icon.style.fontSize = "18px";
                icon.style.fontWeight = "normal";
              }
            }}
          >
            <RightOutlined className="text-lg" style={arrowIconStyle} />
          </button>
        </div>
        <Notice />
      </div>
    </section>
  );
}
